<template lang="pug">
.specimen-info
  LisSpecimen(
    :selectEquipment="currentSpecimen"
    :instrumentId="deviceId"
    :buttonShow="buttonShow"
    :specimenStatus="false"
    ref="specimenRef"
  )
    template(
        #footer
      )
      .actions(
        v-for="(item) in actions"
        ) 
        Button(
          v-for="act in item"
          :key="act.label"
          v-bind="act"
        )

  SpecimenPrint(
    v-model="printModelVisible",
    :specimens="printingSpecimens"
    @printed="onPrinted"
  )

  Cancellation(
    v-model="cancellationModelVisible"
    :selection-row="cancellationSpecimens"
    @canceled="onCanceled"
  )

  ApplicationProject(
    v-model="applyModelVisible"
    :select-equipment="currentSpecimen"
    :instrument-id="deviceId"
    @message-to-parent="onUpdated"
  )
</template>

<script setup lang="ts">
import { type ButtonProps, useNotify, Button } from "@scmt/common-components";
import type { SpecimenEntity } from "@scmt/api-lis-specimen";
import { useApi } from "@scmt/core-api";
import { useRequest } from "@scmt/common-hooks";
import { usePageActions } from "../conposables/actions";
import { SpecimenPrint } from "@scmt/common-api-components";
import { useUtils } from "@scmt/lib-utils";
import { useUser } from "@scmt/common-store";
import LisSpecimen from "../../components/lisSpecimen.vue";
import ApplicationProject from "../../components/applicationProject.vue";
import Cancellation from "../../collection/compoments/cancellation.vue";
import { analysisContextKey } from "../conposables/context";

const analysisContext = inject(analysisContextKey);

if (!analysisContext) {
  throw new Error("analysisContext is required");
}

const props = defineProps({
  specimen: {
    type: Object as PropType<null | SpecimenEntity>,
    default: () => null,
  },
  deviceId: {
    type: String,
    default: "",
  },
});
const emits = defineEmits<{
  "project-updated": [];
  cancelled: [];
  saved: [];
}>();

const $api = useApi();
const $notify = useNotify();
const $utils = useUtils();
const user = useUser();
const {
  printModelVisible,
  printingSpecimens,
  cancellationModelVisible,
  cancellationSpecimens,
  print,
  cancel,
} = usePageActions();
const applyModelVisible = ref(false);
const registrationShow = ref(true);
const buttonShow = ref(true);

const specimenRef = ref<null | InstanceType<typeof LisSpecimen>>(null);
const { specimen, deviceId } = toRefs(props);
const currentSpecimen = ref<SpecimenEntity>($api.lis.specimen.$$createEntity());

const { request, data, loadingMap } = useRequest({
  save: async (model: SpecimenEntity) => {
    // model.specimenProjectList = projectresults.value;
    model.deviceId = deviceId.value;
    return $api.lis.specimen.add(model).then(() => {
      $notify.success("保存成功");

      emits("saved");
    });
  },
  get: (id: string) => $api.lis.specimen.get(id),
  batchGenerateBarcode: async (q: any) => {
    return $api.lis.specimen.batchGenerateBarcode(q).then(() => {
      $notify.success("审核成功");
    });
  },
});

const actions = computed(() => {
  const disabled = !currentSpecimen.value.id;
  const firstRow: ButtonProps[] = [
    {
      label: "结果保存",
      type: "primary",
      disabled,
      loading: loadingMap.save,
      onClick: () => {
        specimenRef.value?.validate((valid, model) => {
          if (valid) {
            const checkResult = analysisContext.getCheckResult();
            request("save", {
              params: Object.assign(model, {
                specimenProjectList: checkResult,
              }),
              onSuccess: () => {
                request("get", {
                  params: model.id,
                  onSuccess: (res) => {
                    $api.lis.specimen.$$createEntity(res);
                  },
                });
              },
            });
          }
        });
      },
    },
    // {
    //   label: "申请加项",
    //   type: "primary",
    //   disabled,
    //   onClick: () => {
    //     applyModelVisible.value = true;
    //   },
    // },
    // {
    //   label: "打印条码",
    //   type: "primary",
    //   disabled,
    //   onClick: () => {
    //     print(currentSpecimen.value!);
    //   },
    // },
    {
      label: "作废",
      type: "primary",
      disabled,
      onClick: () => {
        cancel(currentSpecimen.value!);
      },
    },
  ];

  return [firstRow];
});

watch(specimen, (newVal) => {
  currentSpecimen.value = $api.lis.specimen.$$createEntity(newVal || {});
});

watch(currentSpecimen, () => {
  buttonShow.value = true;
  registrationShow.value = true;

  if (currentSpecimen.value?.id !== specimen.value?.id) {
    analysisContext.setCurrentSpecimen(currentSpecimen.value);
  }
});

const onPrinted = () => {
  printModelVisible.value = false;
};

const onCanceled = () => {
  cancellationModelVisible.value = false;
  emits("cancelled");
};

const onUpdated = () => {
  emits("project-updated");
};
</script>

<style lang="less" scoped>
.specimen-info {
  .actions {
    display: flex;
    justify-content: flex-end;
    margin-bottom: var(--mt-margin-large);
  }
}
</style>
